<template>
  <div class="app-container">
    <v-row :gutter="20">
      <v-col>
        <!-- 搜索表单 -->
        <v-form ref="queryForm" v-show="showSearch" label-width="68px">
          <v-row>
            <v-col md="2" style="padding-bottom: 2px">
              <v-text-field
                label="登录地址"
                v-model="queryParams.ipaddr"
                placeholder="请输入登录地址"
                outlined
                dense
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 240px;"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px">
              <v-text-field
                label="用户名称"
                v-model="queryParams.userName"
                placeholder="请输入用户名称"
                hide-details="auto"
                outlined
                dense
                style="width: 240px;"
                @keyup.enter.native="handleQuery"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px;max-width: 150px">
              <v-select
                label="状态"
                v-model="queryParams.status"
                :items="statusOptions"
                item-text="dictLabel"
                item-value="dictValue"
                placeholder="登录状态"
                dense
                outlined
                clearable
                style="width: 130px;"
              ></v-select>
            </v-col>
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 2px;max-width: 180px">
              <v-menu
                ref="dateRangeMenu"
                v-model="dateRangeMenu"
                :close-on-content-click="false"
                transition="scale-transition"
                offset-y
                max-width="240px"
                min-width="auto"
                style="width: 240px;padding-top: 0;margin-top: 0"
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-text-field
                    v-model="date"
                    label="登录时间"
                    prepend-icon="mdi-calendar"
                    v-bind="attrs"
                    @blur="date = parseDate(dateFormatted)"
                    v-on="on"
                    clearable
                    style="width: 240px;padding-top: 0"
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="date"
                  no-title
                  @input="dateRangeMenu = false"
                  style="padding: 0"
                ></v-date-picker>
              </v-menu>
            </v-col>

            <!-- 按钮区-->
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 0;margin-left: 1rem;height: 40px;margin-top: 8px">
              <p style="display: inline-block;position: absolute">
                <v-btn
                  small color="primary"
                  :loading="loading"
                  @click="handleQuery">
                  <v-icon left>
                    mdi-magnify
                  </v-icon>
                  搜索
                </v-btn>
                <v-btn
                  small
                  :loading="loading"
                  @click="resetQuery"
                  style="margin-left: 10px"
                >
                  <v-icon left>
                    mdi-autorenew
                  </v-icon>
                  重置
                </v-btn>
              </p>
            </v-col>
          </v-row>
        </v-form>
      </v-col>
    </v-row>

    <!-- 表格操作按钮区 -->
    <v-row style="margin-bottom: -5px;margin-top: 0;">
      <!--二次确认删除按钮 -->
      <v-col md="1" style="max-width: 84px">
        <span v-if="!showConfirmDelete">
          <v-btn color="#C62828"
                 small
                 plain
                 outlined
                 :disabled="multiple"
                 @click="onClickDelete()"
                 v-hasPermi="['system:logininfor:remove']">
            <v-icon left>
              mdi-delete
            </v-icon>
            删除
          </v-btn>
        </span>
        <span v-else>
          <v-tooltip top style="z-index: 1000">
            <template v-slot:activator="{ on, attrs }">
              <v-btn
                small color="error"
                plain
                outlined
                :disabled="multiple"
                v-bind="attrs"
                v-on="on"
                @click="handleDelete()"
                v-hasPermi="['system:logininfor:remove']">
                <v-icon left>
                  mdi-delete
                </v-icon>
                确定
              </v-btn>
            </template>
            <span>请再次点击确定删除</span>
          </v-tooltip>
        </span>
      </v-col>
      <v-col md="1" style="max-width: 84px">
        <span v-if="!showConfirmClean">
          <v-btn color="#C62828"
                 small
                 plain
                 outlined
                 @click="onClickClean()"
                 v-hasPermi="['system:logininfor:remove']">
            <v-icon left>
              mdi-delete-variant
            </v-icon>
            清空
          </v-btn>
        </span>
        <span v-else>
          <v-tooltip top>
            <template v-slot:activator="{ on, attrs }">
              <v-btn
                small color="error"
                plain
                outlined
                v-bind="attrs"
                v-on="on"
                @click="handleClean()"
                v-hasPermi="['system:logininfor:remove']">
                <v-icon left>
                  mdi-delete-variant
                </v-icon>
                确定
              </v-btn>
            </template>
            <span>请再次点击确定清空</span>
          </v-tooltip>
        </span>
      </v-col>
      <v-col md="1" style="max-width: 84px">
        <v-btn
          type="warning"
          small
          plain
          outlined
          @click="handleExport"
          v-hasPermi="['system:logininfor:export']">
          <v-icon left>
            mdi-upload
          </v-icon>
          导出
        </v-btn>
      </v-col>
      <v-col style="float: right">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </v-col>
    </v-row>

    <!-- 表格-->
    <v-main>
      <v-data-table v-if="list"
                    v-model="ids"
                    :headers="headers"
                    :items="list"
                    :items-per-page="queryParams.pageSize"
                    hide-default-footer
                    :loading="loading"
                    loading-text="加载中,请稍后.."
                    show-select
                    item-key="infoId"
                    class="elevation-1"
                    no-data-text="暂无数据"
      >
        <!-- 状态插槽 -->
        <template v-slot:item.status="{ item }">
          {{ statusFormat(item) }}
        </template>
        <!-- 访问时间 -->
        <template v-slot:item.accessTime="{ item }">
           {{ parseTime(item.accessTime) }}
        </template>
      </v-data-table>

      <!-- 外部分页-->
      <div class="d-flex align-center justify-end text-center">
        <div class="d-flex" style="margin-top: 3px;font-size: 14px;font-weight: 400">
          <span>每页</span>
          <v-select
            v-model="queryParams.pageSize"
            :items="numbers"
            dense
            @change="getList" style="max-width: 80px;max-height: 20px;margin-top: -4px;text-align: center;">
            <template v-slot:selection="{ item, index }">
                  <span style="width: 100%">
                    {{item}}
                  </span>
            </template>
          </v-select>
          <span>条记录</span>
        </div>
        <v-pagination
          v-model="queryParams.pageNum"
          @input="getList"
          :length="queryParams.totalPages"
          :total-visible="7"
        ></v-pagination>
      </div>
    </v-main>
  </div>
</template>

<script>
import { list, delloginLog, cleanloginLog } from "@/api/system/loginLog";
import { commonUtils } from "@/utils/commonUtils";

export default {
  name: "Logininfor",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 状态数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ipaddr: undefined,
        userName: undefined,
        status: undefined,
        totalPages: 0, // 总页数
      },
      showConfirmDelete: false,
      showConfirmClean: false,
      numbers: [10, 15, 20, 50, 100], // 每页条数选择
      headers: [
        { text: '访问编号', value: 'infoId', align: 'center' },
        { text: '用户名称', value: 'userName', sortable: false, align: 'center' },
        { text: '地址', value: 'ipaddr', sortable: false, align: 'center' },
        { text: '状态', value: 'status', align: 'center' },
        { text: '状态描述', value: 'msg', align: 'center' },
        { text: '访问时间', value: 'accessTime', sortable: false, align: 'center', width: '180px' },
      ],
      date: null,
      dateRangeMenu: false,
      dateFormatted: commonUtils.formatDate((new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000)).toISOString().substr(0, 10)),
    };
  },
  watch: {
    ids() {
      this.handleSelectionChange();
    },
    date (val) {
      this.dateFormatted = this.formatDate(this.date)
    },
  },
  created() {
    this.getList();
    this.getDicts("sys_common_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询登录日志列表 */
    getList() {
      this.ids = [];
      this.loading = true;
      list(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.queryParams.totalPages = Math.ceil(this.total / this.queryParams.pageSize);
        this.loading = false;
      });
    },
    // 登录状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.date) {
        this.queryParams.createTime = this.date;
      } else {
        this.queryParams.createTime = null;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.reset(); // 重置
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange() {
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
    },
    // 表格列点击删除按钮，切换确定删除按钮
    onClickDelete() {
      this.showConfirmDelete = true;
      setTimeout(() => {
        this.showConfirmDelete = false;
      }, 4000);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      // 关闭上一个消息弹窗
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      const infoIds = row.infoId || this.ids.map(item => item.infoId);
        await delloginLog(infoIds).then(res => {
          if (res) {
            // 使用全局消息提示
            this.$store.dispatch('snackbar/openSnackbar', {
              msg: '删除成功',
              color: 'success'
            })
            this.$nextTick(() => {
              this.showConfirmDelete = false;
            })
            this.getList();
          }
        })
    },
    onClickClean() {
      this.showConfirmClean = true;
      setTimeout(() => {
        this.showConfirmClean = false;
      }, 4000);
    },
    /** 清空按钮操作 */
    async handleClean() {
      // 关闭上一个消息弹窗
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      await cleanloginLog().then(res => {
        if (res) {
          // 使用全局消息提示
          this.$store.dispatch('snackbar/openSnackbar', {
            msg: '清空成功',
            color: 'success'
          })
          this.$nextTick(() => {
            this.showConfirmClean = false;
          })
          this.getList();
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/logininfor/export', {
        ...this.queryParams
      }, `logininfor_${new Date().getTime()}.xlsx`)
    },
    // 创建时间 日期格式化
    formatDate (date) {
      if (!date) return null
      const [year, month, day] = date.split('-')
      return `${month}/${day}/${year}`
    },
    parseDate (date) {
      if (!date) return null
      const [month, day, year] = date.split('/')
      return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
    },
  }
};
</script>

